package com.chen.tliaswebtest.controller;

import com.chen.tliaswebtest.annotation.LogOperation;
import com.chen.tliaswebtest.pojo.EmpDTO;
import com.chen.tliaswebtest.pojo.PageResult;
import com.chen.tliaswebtest.pojo.Result;
import com.chen.tliaswebtest.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

/**
 * @author chen
 * @version 1.0
 * @create_date 2025/7/24
 * 员工管理控制层
 */
@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {
    private final EmpService empService;

    public EmpController(EmpService empService) {
        this.empService = empService;
    }

    // 员工列表数据的条件分页查询
    @GetMapping
    public Result list(String name, Integer gender,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        PageResult result = empService.listByPage(name, gender, begin, end, page, pageSize);
        return Result.success(result);
    }

    // 批量删除员工的数据信息
    @DeleteMapping
    @LogOperation
    public Result removeEmps(@RequestParam("ids") List<Integer> ids) {
        empService.removeByIds(ids);
        return Result.success();
    }

    // 添加员工的信息
    @PostMapping
    @LogOperation
    public Result addEmp(@RequestBody EmpDTO inDTO) {
        if (checkRequired(inDTO.getUsername())) {
            return Result.error("用户名不能为空");
        }
        if (checkRequired(inDTO.getName())) {
            return Result.error("员工姓名不能为空");
        }
        if (checkRequired(inDTO.getGender())) {
            return Result.error("员工性别不能为空");
        }

        empService.addEmp(inDTO);
        return Result.success();
    }

    // 根据主键ID查询员工的信息
    @GetMapping("/{id}")
    public Result getEmpById(@PathVariable Integer id) {
        return Result.success(empService.getEmpById(id));
    }

    // 修改员工的数据信息
    @PutMapping
    @LogOperation
    public Result updateEmp(@RequestBody EmpDTO inDTO) {
        empService.updateEmp(inDTO);
        return Result.success();
    }

    // 查询全部员工信息
    @GetMapping("/list")
    public Result getAllEmp() {
        return Result.success(empService.getAllEmp());
    }

    // 判断必须添加的字段是否为空
    private boolean checkRequired(Object obj) {
        return !Objects.nonNull(obj);
    }
}
